package org.oneboot.core.lang.spring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

@Service
public class SpringContextUtil implements ApplicationContextAware {

	private static final Logger logger = LoggerFactory.getLogger(SpringContextUtil.class);
	/**
	 * 以静态变量保存ApplicationContext,可在任意代码中取出ApplicaitonContext.
	 */
	private static ApplicationContext context;

	/**
	 * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
	 * 
	 * @param context
	 */
	@Override
	public void setApplicationContext(ApplicationContext context) {
		SpringContextUtil.context = context;
	}

	/**
	 * 获取容器
	 * 
	 */
	public static ApplicationContext getContext() {
		return context;
	}

	/**
	 * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
	 * 
	 * @param name
	 * @return T
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {
		try {
			return (T) context.getBean(name);
		} catch (NoSuchBeanDefinitionException e) {
			logger.error(e.getMessage(), e);
			return null;
		}

	}
}
